package com.techsoul.module.accounting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.MapUtils;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.log.annotation.Log;
import com.techsoul.common.log.enums.OperationTypeEnum;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.pojo.param.AccApSkuMonthlySettlementSaveParam;
import com.techsoul.module.accounting.pojo.param.AccApSkuMonthlySettlementSearchParam;
import com.techsoul.module.accounting.pojo.param.AccountingApSearchParam;
import com.techsoul.module.accounting.pojo.vo.AccApSkuMonthlySettlementViewVo;
import com.techsoul.module.accounting.pojo.vo.AccApSkuMonthlySettlementVo;
import com.techsoul.module.accounting.pojo.vo.AccountingApViewVo;
import com.techsoul.module.accounting.service.IAccApSkuMonthlySettlementService;
import com.techsoul.module.order.pojo.param.SalesOrderItemSearchParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 财务月度sku汇总 Controller
 *
 * @author liuen
 * @date 2021-06-01
 */
@Api(tags = "财务月度sku汇总")
@RestController
@RequestMapping("/accounting/accApSkuMonthlySettlement")
public class AccApSkuMonthlySettlementController {

    @Autowired
    private Result result;

    @Autowired
    private IAccApSkuMonthlySettlementService service;

    @Autowired
    private TokenService tokenService;

    @ApiOperation("新增")
    @Log(title = "财务月度sku汇总", operationType = OperationTypeEnum.INSERT)
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody AccApSkuMonthlySettlementSearchParam params) {
        this.service.insert(params);
        return result.success();
    }


    @ApiOperation("批量删除（多个用逗号隔开）")
    @Log(title = "财务月度sku汇总", operationType = OperationTypeEnum.DELETE)
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        return result.success(this.service.batchDelete(Arrays.asList(ids)));
    }

    @ApiOperation("修改")
    @Log(title = "财务月度sku汇总", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:update')")
    @PutMapping
    public Result update(@Valid @RequestBody AccApSkuMonthlySettlementSaveParam params) {
        return result.success(this.service.update(params));
    }

    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/search")
    public Result findAll(@RequestBody AccApSkuMonthlySettlementSearchParam params) {
        return result.success(this.service.findAll(params));
    }

    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        //    if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())
        //       &&StringUtils.isNull(params.getStoreId())&&StringUtils.isNull(params.getCustSkuId())
        //        &&StringUtils.isNull(params.getCustSpuId())) {
        //  IPage<AccApSkuMonthlySettlementVo> rt = this.service.findAll(params, current, pageSize);
        //     return result.success(rt);
        //  }       else
     /*  if(StringUtils.isNull(params.getCustSpuId())&&StringUtils.isNull(params.getCustSkuId())
               &&StringUtils.isNull(params.getStoreId())){
           IPage<AccApSkuMonthlySettlementVo> rt = this.service.findAll(params, current, pageSize);
           return result.success(rt);

       }else{*/
        IPage<AccApSkuMonthlySettlementVo> rt = this.service.findAll(params, current, 20000);

        List<AccApSkuMonthlySettlementViewVo> sum = this.service.reportSum(params);
        if(sum!=null&&sum.size()>0){
            AccApSkuMonthlySettlementViewVo accApSkuMonthlySettlementViewVo =
                    (AccApSkuMonthlySettlementViewVo)sum.get(0);
            if(accApSkuMonthlySettlementViewVo!=null) {
                AccApSkuMonthlySettlementVo accApSkuMonthlySettlementVo = new AccApSkuMonthlySettlementVo();
                accApSkuMonthlySettlementVo.setJobMonth("合计：");
                if (accApSkuMonthlySettlementViewVo.getSumAmtCur() != null) {
                    accApSkuMonthlySettlementVo.setAmtCur(new BigDecimal(accApSkuMonthlySettlementViewVo.getSumAmtCur()));
                }
                accApSkuMonthlySettlementVo.setCustMilePaymentAmt(accApSkuMonthlySettlementViewVo.getSumCustMilePaymentAmt());
                accApSkuMonthlySettlementVo.setCustCashPaymentAmt(accApSkuMonthlySettlementViewVo.getSumCustCashPaymentAmt());
                if (accApSkuMonthlySettlementViewVo.getSumOriginalSellQty() != null) {
                    accApSkuMonthlySettlementVo.setOriginalSellQty(Integer.valueOf(accApSkuMonthlySettlementViewVo.getSumOriginalSellQty().intValue()));
                }
                if (accApSkuMonthlySettlementViewVo.getSumQty() != null) {
                    accApSkuMonthlySettlementVo.setWtCnt(new BigDecimal(accApSkuMonthlySettlementViewVo.getSumQty()));
                }
                if (accApSkuMonthlySettlementViewVo.getSumAmount() != null) {
                    accApSkuMonthlySettlementVo.setAmount(new BigDecimal(accApSkuMonthlySettlementViewVo.getSumAmount()));
                }
                if (accApSkuMonthlySettlementViewVo.getSumAmtAr() != null) {
                    accApSkuMonthlySettlementVo.setAmtAr(new BigDecimal(accApSkuMonthlySettlementViewVo.getSumAmtAr()));
                }

                accApSkuMonthlySettlementVo.setReturnAmt(accApSkuMonthlySettlementViewVo.getSumReturnAmt());
                if (accApSkuMonthlySettlementViewVo.getSumReturnQty() != null) {
                    accApSkuMonthlySettlementVo.setReturnQty(Integer.valueOf(accApSkuMonthlySettlementViewVo.getSumReturnQty().intValue()));
                }
                rt.getRecords().add(0, accApSkuMonthlySettlementVo);
            }
        }


        return result.success(rt);
        //  }


     /*   String today = DateUtils.getDate();
        String day = today.split("-")[2];
        String mon = today.split("-")[1];
        String year = today.split("-")[0];
        int dt = Integer.valueOf(day);
        int month = Integer.valueOf(mon);
        int yr =  Integer.valueOf(year);
        if(dt>=15){ // 15号以前不考虑新生成报表
            List<AccApSkuMonthlySettlementVo> rcds = rt.getRecords();
            if(month==1) {
                month = 12;
            }else{
                month = month-1;
            }
            if(rcds!=null&&rcds.size()>0){
                AccApSkuMonthlySettlementVo accApSkuMonthlySettlementVo = rcds.get(0);
                String jbmonth = accApSkuMonthlySettlementVo.getJobMonth();

                String jbyr = jbmonth.split("-")[0];
                String jbmon = jbmonth.split("-")[1];
                int intmonth = Integer.valueOf(jbmon);

                if(month>intmonth){ // 上个月报表不存在
                   this.service.generateMonthlySum(month,yr, params, user);   //生成先
                    rt = this.service.findAll(params, current, pageSize);
                }

            }// end record null
            else{ //没有报表 要生成

               this.service.generateMonthlySum(month,yr,params, user);
                rt = this.service.findAll(params, current, pageSize);
            }

        }//end if 15 前*/


    }

    @ApiOperation("导出")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/exportData")
    public Result exportData(@RequestBody AccApSkuMonthlySettlementSearchParam params) {
        return result.success(this.service.exportData(params));
    }

    @ApiOperation("品牌排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/brandRateView/{current}/{pageSize}")
    public Result brandRateView(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-02-28");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,183);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }

        return result.success(this.service.brandRateView(params, current, 10000));
    }

    @ApiOperation("spu排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/spuRateView/{current}/{pageSize}")
    public Result spuRateView(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {

        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-02-28");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,183);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }
        return result.success(this.service.spuRateView(params, current, 4000));
    }
    @ApiOperation("供应商排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/supplierRateView/{current}/{pageSize}")
    public Result supplierRateView(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {

        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-02-28");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,183);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }
        return result.success(this.service.supplierRateView(params, current, 1000));
    }
    @ApiOperation("店铺排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/storeRateView/{current}/{pageSize}")
    public Result storeRateView(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-02-28");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,183);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }

        return result.success(this.service.storeRateView(params));
    }

    @ApiOperation("单品销售分析列表")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/skuSpuRateReport/{current}/{pageSize}")
    public Result skuSpuRateReport(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-07-31");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,365);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }
        IPage<AccApSkuMonthlySettlementViewVo> ipages = this.service.skuSpuRateReport(params, current, 1000);
        return result.success(ipages);
    }

    @ApiOperation("单品销售分析列表")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/skuSpuRateChartReport/{current}/{pageSize}")
    public Result skuSpuRateChartReport(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-07-31");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,365);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }
        IPage<AccApSkuMonthlySettlementViewVo> ipages = this.service.skuSpuRateReport(params, current, 1000);
//        String xdata = "{ title:'单品月销售', xData:[";
//        String ydata = " yData:[";
//        String zdata = " zData:[";
        List <AccApSkuMonthlySettlementViewVo> accApSkuMonthlySettlementViewVos =ipages.getRecords();
//        for(int i=0; i < accApSkuMonthlySettlementViewVos.size();i++){
//            AccApSkuMonthlySettlementViewVo accApSkuMonthlySettlementViewVo =(AccApSkuMonthlySettlementViewVo)accApSkuMonthlySettlementViewVos.get(i);
//            if(i==accApSkuMonthlySettlementViewVos.size()-1){
//                xdata = xdata.concat("'").concat(accApSkuMonthlySettlementViewVo.getJobMonth()).concat("'],");
//                ydata = ydata.concat(String.valueOf(accApSkuMonthlySettlementViewVo.getSumAmtAr())).concat("],");
//                zdata = zdata.concat(String.valueOf(accApSkuMonthlySettlementViewVo.getSumQty())).concat("]");
//            }else{
//                xdata = xdata.concat("'").concat(accApSkuMonthlySettlementViewVo.getJobMonth()).concat("',");
//                ydata = ydata.concat(String.valueOf(accApSkuMonthlySettlementViewVo.getSumAmtAr())).concat(",");
//                zdata = zdata.concat(String.valueOf(accApSkuMonthlySettlementViewVo.getSumQty())).concat(",");
//            }
//        }
//        String rest = xdata.concat(ydata).concat(zdata).concat("}");
        Map<String, Object> rest = MapUtils.newHashMap();
        List<String> xdata = accApSkuMonthlySettlementViewVos.stream().map(AccApSkuMonthlySettlementViewVo::getJobMonth).collect(Collectors.toList());
        List<Double> ydata = accApSkuMonthlySettlementViewVos.stream().map(AccApSkuMonthlySettlementViewVo::getSumAmtAr).collect(Collectors.toList());
        List<Double> zdata = accApSkuMonthlySettlementViewVos.stream().map(AccApSkuMonthlySettlementViewVo::getSumQty).collect(Collectors.toList());
        rest.put("title", "单品日销售");
        rest.put("xData", xdata);
        rest.put("yData", ydata);
        rest.put("zData", zdata);
        return result.success(rest);
    }

    @ApiOperation("单品销售排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/skuRateView/{current}/{pageSize}")
    public Result skuRateView(@RequestBody AccApSkuMonthlySettlementSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        if(StringUtils.isNull(params.getJobMonthFr())&&StringUtils.isNull(params.getJobMonthTo())){
            Date today = new Date();
            Date ayear = DateUtils.parseDate("2022-07-31");
            if(today.after(ayear)){
                String thismonth = DateUtils.formatDate(today,"yyyy-MM");
                Date frdate = DateUtils.getDateBefore(today,365);
                String monthFr = DateUtils.formatDate(today,"yyyy-MM");
                params.setJobMonthFr(monthFr);
                params.setJobMonthTo(thismonth);
            }
        }
        return result.success(this.service.skuRateView(params, current, pageSize));
    }

    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/countTotalPurchase")
    public Result countTotalPurchase() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccApSkuMonthlySettlementSearchParam accApSkuMonthlySettlementSearchParam = new AccApSkuMonthlySettlementSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        //  accApSkuMonthlySettlementSearchParam.setJobMonth(thismon);
        return result.success(this.service.countTotalPurchase(accApSkuMonthlySettlementSearchParam));
    }
    @ApiOperation("采购和销售按月统计")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/countMonthlyLineChart")
    public Result countMonthlyLineChart() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccApSkuMonthlySettlementSearchParam accApSkuMonthlySettlementSearchParam = new AccApSkuMonthlySettlementSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();
        Double start = NumberUtils.sub(Double.valueOf(mon),6.0);
        String startyear =  "";
        if(start<=0){
            start = NumberUtils.add(12.0,start);
            Double starty = NumberUtils.sub(Double.valueOf(year),1.0);
            startyear = String.valueOf(starty);
        }else{
            startyear = year;
        }

        Double starty = NumberUtils.sub(Double.valueOf(year),1.0);
        Integer startye = starty.intValue();
        startyear = String.valueOf(startye);
        String thismon = year.concat("-").concat(mon);
        // 多减1年，显示24个月
        startyear = String.valueOf(Integer.valueOf(startyear)-1);
        String StartMon = startyear.concat("-").concat(mon);
        AccApSkuMonthlySettlementSearchParam params = new AccApSkuMonthlySettlementSearchParam ();
        params.setJobMonthFr(StartMon);
        params.setJobMonthTo(thismon);
        return result.success(this.service.countMonthlyLineChart(params));
    }
    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/countMonthTotalPurchase")
    public Result countMonthTotalPurchase() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccApSkuMonthlySettlementSearchParam accApSkuMonthlySettlementSearchParam = new AccApSkuMonthlySettlementSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        accApSkuMonthlySettlementSearchParam.setJobMonth(thismon);
        return result.success(this.service.countTotalPurchase(accApSkuMonthlySettlementSearchParam));
    }
    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/countTotalSale")
    public Result countTotalSale() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccApSkuMonthlySettlementSearchParam accApSkuMonthlySettlementSearchParam = new AccApSkuMonthlySettlementSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        //  accApSkuMonthlySettlementSearchParam.setJobMonth(thismon);
        return result.success(this.service.countTotalSale(accApSkuMonthlySettlementSearchParam));
    }
    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/countMonthTotalSale")
    public Result countMonthTotalSale() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccApSkuMonthlySettlementSearchParam accApSkuMonthlySettlementSearchParam = new AccApSkuMonthlySettlementSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        accApSkuMonthlySettlementSearchParam.setJobMonth(thismon);
        return result.success(this.service.countTotalSale(accApSkuMonthlySettlementSearchParam));
    }

    @ApiOperation("查询汇总")
    @PreAuthorize("hasAnyAuthority('accounting:accApSkuMonthlySettlement:search')")
    @PostMapping("/reportSum")
    public Result reportSum(@RequestBody AccApSkuMonthlySettlementSearchParam params) {
        return result.success(this.service.reportSum(params));
    }
}
